import Koa from 'koa';
import Router from 'koa-router'
import { sync } from './db/index.js'
import { User } from './model/User.js';
import bodyParser from 'koa-bodyparser';
import koaCors from 'koa-cors';
import { Op } from 'sequelize';

const reqPath = "http://localhost:3000"

const app = new Koa();

sync()

app.use(koaCors())

app.use(bodyParser())

const router = new Router()

router.get("/users", async (ctx) => {
    let keyword = ctx.query.keyword
    console.log(keyword);

    let users;

    if(keyword){
        users = await User.findAll({where:{
            [Op.or]:{
                uname:{
                    [Op.like]:`%${keyword}%`
                },
                uage:{
                    [Op.like]:`%${keyword}%`
                },
            }
        }})
    }else{
        users = await User.findAll()
    }
    
    
    ctx.body = {
        code: 200,
        msg: "请求所有",
        data: users
    }
})

router.get("/user/:id", async (ctx) => {
    let id = ctx.params.id
    let user = await User.findByPk(id)
    ctx.body = {
        code: 200,
        msg: "请求单个",
        data: user
    }
})

router.delete("/user/:id", async (ctx) => {
    let id = ctx.params.id
    await User.destroy({where:{id}})
    ctx.body = {
        code: 200,
        msg: "删除",
        data: null
    }
})
router.post("/user", async (ctx) => {
    const obj = ctx.request.body
    await User.create(obj)
    console.log("新增用户");
    
    ctx.body = {
        code: 200,
        msg: "新增",
        data: null
    }
})
router.put("/user/:id", async (ctx) => {
    let id = ctx.params.id
    let obj = ctx.request.body
    await User.update(obj,{where:{id}})
    ctx.body = {
        code: 200,
        msg: "修改",
        data: null
    }
})

app.use(router.routes())

app.listen(3000, () => {
    console.log(`服务运行如下地址: \n${reqPath}`);
})